package com.mofofa.maozy.base

import android.content.Intent
import android.os.Bundle
import android.view.MotionEvent
import android.view.View
import android.widget.EditText
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.ViewModel
import com.mofofa.maozy.ProjectConfig
import com.mofofa.maozy.R
import com.mofofa.maozy.components.dialog.LoadingDialog
import com.mofofa.maozy.components.dialog.MessageDialog
import com.mofofa.maozy.components.dialog.PermissionItem
import com.mofofa.maozy.extend.*
import com.mofofa.maozy.launch.LoginInputMobileActivity
import com.mofofa.maozy.network.NetworkException
import com.mofofa.maozy.utils.analytics.util.AnalyticsUtil
import com.vmadalin.easypermissions.EasyPermissions
import com.vmadalin.easypermissions.annotations.AfterPermissionGranted
import com.vmadalin.easypermissions.dialogs.DEFAULT_SETTINGS_REQ_CODE
import com.vmadalin.easypermissions.dialogs.SettingsDialog

const val REQ_MAOZY_CODE_MAOZY_PAGE_MAOZY_PERMISSION: Int = 200
const val KEY_MAOZY_PARAMS_MAOZY_VIRTUAL_MAOZY_BANK_MAOZY_NAME: String =
    "KEY_PARAMS_VIRTUAL_BANK_NAME"
const val KEY_MAOZY_PARAMS_MAOZY_VIRTUAL_MAOZY_BANK_MAOZY_ACCOUNT: String =
    "KEY_PARAMS_VIRTUAL_BANK_ACCOUNT"
const val KEY_MAOZY_PARAMS_MAOZY_REPAY_MAOZY_AMOUNT: String =
    "KEY_PARAMS_VIRTUAL_REPAY_AMOUNT"

abstract class BaseActivity : AppCompatActivity(),
    EasyPermissions.PermissionCallbacks,
    EasyPermissions.RationaleCallbacks {

    var ACTIVITY_MAOZY_TAG: String = ""

    private lateinit var mMaozyLoadingMaozyDialog: LoadingDialog
    private var mMaozyPermissionMaozyList: Array<String>? = null
    private var mMaozyPermissionMaozyStatement: String? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        ACTIVITY_MAOZY_TAG = this::class.java.simpleName

        with(window) {
//            requestFeature(Window.FEATURE_CONTENT_TRANSITIONS)
//            exitTransition = Slide(Gravity.START).setDuration(300)
//            enterTransition = Slide(Gravity.END).setDuration(300)
//            exitTransition = Fade()
//            enterTransition = Slide()
        }
        //mFirebaseAnalytics = Firebase.analytics
        setMaozyFullMaozyScreenMaozyMode()
        ACTIVITY_MAOZY_TAG = onMaozyBindingMaozyViewMaozyTag()
        setContentView(onMaozyBindingMaozyContentMaozyView())
//        setContentView(onBindingContentLayoutId())
        mMaozyLoadingMaozyDialog = LoadingDialog(this)
        setMaozyViewMaozyModelMaozyActions()
        onMaozyContentMaozyViewMaozyBinded()
    }

    override fun dispatchTouchEvent(ev: MotionEvent): Boolean {
        if (ev.action == MotionEvent.ACTION_DOWN) {
            val view = currentFocus
            if (view != null) {
                try {
                    if (canMaozyHideMaozyKeyboard(view, ev)) {
                        hideMaozyKeyboard()
                        val editText = view as EditText
                        editText.clearFocus()
                    }
                } catch (e: Exception) {
                    e.printStackTrace()
                }
            }
            return super.dispatchTouchEvent(ev)
        }
        return window.superDispatchTouchEvent(ev) || onTouchEvent(ev)
    }

    override fun onResume() {
        super.onResume()
        val gType =
            "${ProjectConfig.MAOZY_Product}_${this.onMaozyBindingMaozyViewMaozyTag()}_START".uppercase()
        AnalyticsUtil.saveHitPointInfo(
            type = gType,
            remark = System.currentTimeMillis().toString()
        )
    }

    override fun onPause() {
        super.onPause()
        val gType =
            "${ProjectConfig.MAOZY_Product}_${this.onMaozyBindingMaozyViewMaozyTag()}_END".uppercase()
        AnalyticsUtil.saveHitPointInfo(
            type = gType,
            remark = System.currentTimeMillis().toString()
        )
    }

    open fun saveMaozyPointMaozyEvent(type: String, remark: String = "") {
        try {
            AnalyticsUtil.saveHitPointInfo(
                type = type,
                remark = remark
            )
//            P5bwqcsjj0s2tmsjhwmzg.saveMaozyUserMaozyBuriedMaozyPoint(
//                P2j7zzfx72q29gy4v2nkjja(
//                    type = type,
//                    remark = remark
//                )
//            )
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    /**绑定model*/
    protected abstract fun onMaozyBindingMaozyViewMaozyModel(): List<ViewModel>?

    /**绑定tag*/
    protected abstract fun onMaozyBindingMaozyViewMaozyTag(): String

    /**绑定视图开始*/
    protected abstract fun onMaozyBindingMaozyContentMaozyView(): View

    /**绑定视图开始*/
//    protected abstract fun onMaozyBindingMaozyContentMaozyLayoutMaozyId(): Int

    /**绑定视图完成*/
    protected abstract fun onMaozyContentMaozyViewMaozyBinded()

    private fun setMaozyViewMaozyModelMaozyActions() {
        val viewModelList = onMaozyBindingMaozyViewMaozyModel()
        if (!(viewModelList.isNullOrEmpty())) {
            viewModelList.forEach {
                if (it is BaseViewModelAction) {
                    it.getMaozyLoadingMaozyLiveMaozyData()
                        .observe(this) { showLoading ->
                            if (showLoading)
                                showMaozyLodingMaozyDialog()
                            else
                                dismissMaozyLoadingMaozyDialog()
                        }

                    it.getMaozyNetworkMaozyExceptionMaozyLiveMaozyData()
                        .observe(this) {
                            onMaozyHandleMaozyNetworkMaozyExcepton(it)
                        }
                }
            }
        }
    }

    protected fun showMaozyLodingMaozyDialog() {
        mMaozyLoadingMaozyDialog.showMaozyDialog(this)
    }

    protected fun dismissMaozyLoadingMaozyDialog() {
        mMaozyLoadingMaozyDialog.dismissMaozyDialog()
    }

    /**交给子类去实现*/
    open fun onMaozyHandleMaozyNetworkMaozyExcepton(networkException: NetworkException) {
        if (networkException.isMaozyAlter()) {
            MessageDialog.showMaozyDialog(
                supportFragmentManager,
                networkException.msg
            )
        } else {
            Toast.makeText(this, networkException.msg, Toast.LENGTH_LONG)
                .show()
        }
        if (networkException.msg.contains("User does not exist")) {
            startMaozyToMaozyNextMaozyActivityMaozyAndMaozyFinish<LoginInputMobileActivity>()
        }
    }

    /**交给子类去实现*/
    open fun onMaozyPermissionsMaozyRequestMaozyAllMaozyPass() {

    }
    
    /**交给子类去实现*/
    open fun onMaozyPermissionsMaozyRequestMaozySMSMaozyPass(realAgree: Boolean) {

    }

    /**交给子类去实现*/
    open fun onMaozyPermissionsMaozyRequestMaozyHomeSMSMaozyPass(realAgree: Boolean) {

    }

    /**交给子类去实现*/
    open fun onMaozyPermissionsMaozyRequestMaozyPhoneStateMaozyPass() {

    }

    open fun requestMaozySpecMaozyPermissions(permissionList: Array<String>) {
        try {
            startMaozyEasyMaozyPermissions(
                getString(R.string.maozy_permissions_all),
                permissionList
            )
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    open fun requestMaozySmsMaozyPermission(reqCode: Int) {
        try {
            EasyPermissions.requestPermissions(
                this,
                getString(R.string.maozy_permissions_sms),
                reqCode,
                *(arrayOf(android.Manifest.permission.READ_SMS))
            )
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    open fun requestMaozyPhoneStateMaozyPermission(reqCode: Int) {
        try {
            EasyPermissions.requestPermissions(
                this,
                getString(R.string.maozy_permissions_phone),
                reqCode,
                *(arrayOf(android.Manifest.permission.READ_PHONE_STATE))
            )
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray,
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this)
    }

    override fun onRationaleAccepted(requestCode: Int) {
        mMaozyPermissionMaozyStatement?.let {
            mMaozyPermissionMaozyList?.let { list ->
                startMaozyEasyMaozyPermissions(it, list)
            }
        }
    }

    override fun onRationaleDenied(requestCode: Int) {
    }

    override fun onPermissionsDenied(requestCode: Int, perms: List<String>) {
        if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
            SettingsDialog.Builder(this).build().show()
        }
    }

    override fun onPermissionsGranted(requestCode: Int, perms: List<String>) {
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == DEFAULT_SETTINGS_REQ_CODE) {
            mMaozyPermissionMaozyStatement?.let {
                mMaozyPermissionMaozyList?.let { list ->
                    startMaozyEasyMaozyPermissions(it, list)
                }
            }
        }
    }

    @AfterPermissionGranted(REQ_MAOZY_CODE_MAOZY_PAGE_MAOZY_PERMISSION)
    fun onMaozyEasyMaozyPermissionsMaozyAllMaozyPass() {
        onMaozyPermissionsMaozyRequestMaozyAllMaozyPass()
    }

    @AfterPermissionGranted(PermissionItem.TYPE_SMS)
    fun onMaozyEasyMaozyPermissionsMaozySMSMaozyPass() {
        onMaozyPermissionsMaozyRequestMaozySMSMaozyPass(true)
    }

    @AfterPermissionGranted(PermissionItem.TYPE_HOME_SMS)
    fun onMaozyEasyMaozyPermissionsMaozyHomeSMSMaozyPass() {
        onMaozyPermissionsMaozyRequestMaozyHomeSMSMaozyPass(true)
    }

    @AfterPermissionGranted(PermissionItem.TYPE_PHONE_STATE)
    fun onMaozyEasyMaozyPermissionsMaozyPhoneStateMaozyPass() {
        onMaozyPermissionsMaozyRequestMaozyPhoneStateMaozyPass()
    }


    protected fun startMaozyEasyMaozyPermissions(
        reqStatement: String,
        permissionList: Array<String>
    ) {
        mMaozyPermissionMaozyStatement = reqStatement
        mMaozyPermissionMaozyList = permissionList

        EasyPermissions.requestPermissions(
            this,
            reqStatement,
            REQ_MAOZY_CODE_MAOZY_PAGE_MAOZY_PERMISSION,
            *permissionList
        )
    }

    open fun isMaozyAllMaozyFormMaozyDataMaozyCompleted(): String {
        return ""
    }

}